<template>
  <div class="question-page">
    <div class="question-header">
      <a-button type="text" @click="goBack" class="back-btn">
        <template #icon>
          <IconLeft />
        </template>
        返回章节列表
      </a-button>

      <div class="chapter-info">
        <h2>{{ getChapterTitle(currentChapter) }}</h2>
        <a-progress :percent="progressPercent" size="small" :show-text="false" class="progress-bar" />
      </div>
    </div>

    <div class="question-container">
      <!-- 系统消息显示区域 -->
      <div class="message-area">
        <!-- 欢迎消息 -->
        <div v-if="!hasStarted && !loading" class="welcome-message">
          <div class="message-item bot-message">
            <div class="message-avatar">
              <IconRobot />
            </div>
            <div class="message-content">
              <div class="message-text">欢迎来到{{ getChapterTitle(currentChapter) }}！准备开始训练...</div>
            </div>
          </div>
        </div>

        <!-- 消息列表 -->
        <div v-for="message in displayMessages" :key="message.id" class="message-item" :class="{
          'user-message': message.isUser,
          'bot-message': !message.isUser
        }">
          <!-- 机器人消息：头像在左边 -->
          <template v-if="!message.isUser">
            <div class="message-avatar">
              <IconRobot />
            </div>
            <div class="message-content">
              <div class="message-text">{{ replaceUserName(message.content) }}</div>
              <!-- 问题图片 -->
              <div v-if="message.img" class="message-image">
                <img 
                  :src="getImageUrl(message.img)" 
                  :alt="replaceUserName(message.content)" 
                  class="question-image" 
                  @click="showImageModal(getImageUrl(message.img), replaceUserName(message.content))"
                />
              </div>
            </div>
          </template>

          <!-- 用户消息：头像在右边 -->
          <template v-else>
            <div class="message-content">
              <div class="message-text">{{ replaceUserName(message.content) }}</div>
            </div>
            <div class="message-avatar user-avatar">
              <IconUser />
            </div>
          </template>
        </div>
      </div>

      <!-- 计时器区域 -->
      <div class="timer-area" v-if="shouldShowTimer">
        <div class="timer-display">
          <span class="timer-text">
            <IconClockCircle /> {{ formatTime(timer.remaining) }}
          </span>
          <a-button 
            v-if="!timer.isRunning && !timer.isPaused"
            type="primary"
            size="small"
            @click="startTimer"
          >
            开始
          </a-button>
          <a-button 
            v-if="timer.isRunning"
            size="small"
            @click="pauseTimer"
          >
            暂停
          </a-button>
          <a-button 
            v-if="timer.isPaused"
            type="primary"
            size="small"
            @click="resumeTimer"
          >
            继续
          </a-button>
        </div>
      </div>

      <!-- 选择选项区域 -->
      <div class="choices-area" v-if="shouldShowChoices">
        <h3>请选择：</h3>

        <!-- 实际选择选项 -->
        <div class="choices-grid">
          <div v-for="(choice, index) in currentChoices" :key="choice.id" class="choice-item"
            @click="handleChoiceClick(choice)">
            <div class="choice-number">
              {{ String.fromCharCode(65 + index) }}
            </div>
            <div class="choice-content">
              {{ choice.content }}
            </div>
            <div class="choice-arrow">
              <IconRight />
            </div>
          </div>
        </div>
      </div>

      <!-- 用户输入区域 -->
      <div class="input-area" v-if="shouldShowInput">
        <h3>请输入您的想法：</h3>

        <div class="input-container">
          <a-textarea v-model="userInput" placeholder="请在这里写下您的想法..." :rows="4" :max-length="500" show-word-limit
            @keydown.ctrl.enter="handleInputSubmit" class="user-input" />

          <div class="input-actions">
            <div class="input-hint">
              <IconBulb style="margin-right: 4px;" />
              <span>写下您的真实想法，没有对错之分</span>
            </div>
            <a-button type="primary" size="large" @click="handleInputSubmit" :disabled="!userInput.trim()"
              class="submit-btn">
              提交想法
            </a-button>
          </div>
        </div>
      </div>


      <!-- 加载状态遮罩 -->
      <div class="loading-overlay" v-if="loading">
        <div class="loading-content">
          <a-spin size="large" />
          <p>正在加载章节内容...</p>
        </div>
      </div>
    </div>
    
    <!-- 图片查看模态框 -->
    <a-modal
      v-model:visible="imageModal.visible"
      :footer="false"
      width="auto"
      modal-class="image-modal"
      @cancel="closeImageModal"
    >
      <template #title>
        <span>查看图片</span>
      </template>
      <div class="modal-image-container">
        <img 
          :src="imageModal.src" 
          :alt="imageModal.alt" 
          class="modal-image"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { 
  IconLeft, 
  IconRight, 
  IconRobot, 
  IconUser,
  IconClockCircle,
  IconBulb
} from '@arco-design/web-vue/es/icon'
import { useQuestionStore } from '../../stores/question'
import { useUserStore } from '../../stores/user'
import { scriptApi, userApi } from '../../api'

const route = useRoute()
const router = useRouter()
const questionStore = useQuestionStore()
const userStore = useUserStore()

// 替换文本中的userName为实际用户名
const replaceUserName = (text: string): string => {
  if (!text) return ''
  const userName = userStore.user?.real_name || userStore.user?.username || '用户'
  return text.replace(/userName/g, userName)
}

// 获取图片完整路径（使用 Vite 的 base 路径配置，处理中文路径）
const getImageUrl = (imgPath: string | null | undefined): string => {
  if (!imgPath) return ''
  
  // 分离路径和文件名
  const lastSlashIndex = imgPath.lastIndexOf('/')
  if (lastSlashIndex === -1) {
    // 没有路径，只有文件名
    return encodeURI(imgPath)
  }
  
  const pathPart = imgPath.substring(0, lastSlashIndex + 1) // 包含最后的 /
  const fileName = imgPath.substring(lastSlashIndex + 1)
  
  // 对文件名进行URL编码（处理中文等特殊字符）
  const encodedFileName = encodeURIComponent(fileName)
  
  // import.meta.env.BASE_URL 会自动读取 vite.config.ts 中的 base 配置
  const baseUrl = import.meta.env.BASE_URL.replace(/\/$/, '')
  
  return `${baseUrl}${pathPart}${encodedFileName}`
}

// 章节标题映射
const chapterTitles = {
  0: 'E0 导入',
  1: 'E1 探寻重复消极思维',
  2: 'E2 认识价值与行动选择',
  3: 'E3 跟消极想法说再见',
  4: 'E4 做想法的旁观者',
  5: 'E5 探寻自我与生活方向',
  6: 'E6 行动指南',
  7: 'E7 结束'
}

const getChapterTitle = (nodenum: number) => {
  return chapterTitles[nodenum as keyof typeof chapterTitles] || `第${nodenum}章`
}

// 状态管理
const loading = ref(false)
const hasStarted = ref(false)
const displayMessages = ref<any[]>([])
const userInput = ref('')  // 用户输入内容
const autoNextTimer = ref<number | null>(null)  // 自动跳转定时器
const messageCounter = ref({ total: 0, completed: 0 })  // 消息计数器
const imageModal = reactive({
  visible: false,
  src: '',
  alt: ''
})  // 图片查看模态框

// 计时器相关状态
const timer = reactive({
  total: 0,        // 总时间（秒）
  remaining: 0,    // 剩余时间（秒）
  isRunning: false,
  isPaused: false,
  intervalId: null as number | null
})

// 计算属性
const currentChapter = computed(() => questionStore.currentChapter)
const currentChoices = computed(() => questionStore.getChoices(questionStore.currentAnswerNum))
const needInput = computed(() => questionStore.getNeedInput(questionStore.currentAnswerNum))
const progressPercent = computed(() => {
  if (!questionStore.scripts.length) return 0
  const totalQuestions = Math.max(...questionStore.scripts.map(s => s.answernum))
  return Math.round((questionStore.currentAnswerNum / totalQuestions) * 100)
})

// 控制是否显示选择选项区域
const shouldShowChoices = computed(() => {
  // 如果需要输入框，不显示选择选项
  if (needInput.value) {
    return false
  }
  
  // 如果没有选择选项，不显示
  if (currentChoices.value.length === 0) {
    return false
  }
  
  // 检查是否所有选择项的内容都为空（排除空选项）
  const hasEmptyContent = currentChoices.value.every(choice => !choice.content || choice.content.trim() === '')
  if (hasEmptyContent) {
    console.log('🚫 所有选项内容为空，隐藏选择选项')
    return false
  }
  
  return hasStarted.value
})

// 控制是否显示输入框区域
const shouldShowInput = computed(() => {
  const result = needInput.value && hasStarted.value
  console.log(`🔍 输入框显示检查 - 问题${questionStore.currentAnswerNum}:`, {
    needInput: needInput.value,
    hasStarted: hasStarted.value,
    shouldShow: result
  })
  return result
})

// 获取当前问题的计时器设置
const currentTimer = computed(() => {
  // 先检查系统文本（T类型）
  const systemTexts = questionStore.getSystemTexts(questionStore.currentAnswerNum)
  console.log(`🔍 检查问题${questionStore.currentAnswerNum}的timer:`, {
    systemTexts: systemTexts.length,
    systemTimer: systemTexts[0]?.timer
  })
  
  if (systemTexts.length > 0 && systemTexts[0].timer) {
    console.log(`✅ 从系统文本获取timer: ${systemTexts[0].timer}`)
    return systemTexts[0].timer
  }
  
  // 如果系统文本没有timer，检查选择选项（C类型）
  const choices = questionStore.getChoices(questionStore.currentAnswerNum)
  console.log(`  检查选择选项:`, {
    choices: choices.length,
    choiceTimer: choices[0]?.timer
  })
  
  if (choices.length > 0 && choices[0].timer) {
    console.log(`✅ 从选择选项获取timer: ${choices[0].timer}`)
    return choices[0].timer
  }
  
  console.log(`❌ 未找到timer设置`)
  return null
})

// 控制是否显示计时器
const shouldShowTimer = computed(() => {
  return currentTimer.value && hasStarted.value
})

// 导航函数
const goBack = async () => {
  // 退出问答界面时保存当前位置（属于异常退出）
  if (userStore.user?.id && hasStarted.value) {
    await questionStore.saveCurrentPosition(userStore.user.id)
    console.log('💾 退出问答界面，已保存当前位置:', questionStore.currentAnswerNum)
  }
  
  router.push('/user/chapters')
}

// 清理所有定时器
const cleanupTimers = () => {
  // 清理自动跳转定时器
  if (autoNextTimer.value) {
    clearTimeout(autoNextTimer.value)
    autoNextTimer.value = null
  }
  
  // 清理计时器
  stopTimer()
}

// 格式化时间显示
const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 初始化计时器
const initTimer = () => {
  if (currentTimer.value) {
    timer.total = currentTimer.value
    timer.remaining = currentTimer.value
    timer.isRunning = false
    timer.isPaused = false
    if (timer.intervalId) {
      clearInterval(timer.intervalId)
      timer.intervalId = null
    }
  }
}

// 开始计时
const startTimer = () => {
  if (!currentTimer.value) return
  
  timer.isRunning = true
  timer.isPaused = false
  
  timer.intervalId = window.setInterval(() => {
    if (timer.remaining > 0) {
      timer.remaining--
      
      // 倒计时结束
      if (timer.remaining === 0) {
        stopTimer()
        handleTimerEnd()
      }
    }
  }, 1000)
}

// 暂停计时
const pauseTimer = () => {
  timer.isRunning = false
  timer.isPaused = true
  
  if (timer.intervalId) {
    clearInterval(timer.intervalId)
    timer.intervalId = null
  }
}

// 继续计时
const resumeTimer = () => {
  if (timer.isPaused) {
    startTimer()
  }
}

// 停止计时
const stopTimer = () => {
  timer.isRunning = false
  timer.isPaused = false
  
  if (timer.intervalId) {
    clearInterval(timer.intervalId)
    timer.intervalId = null
  }
}

// 计时器结束处理
const handleTimerEnd = async () => {
  console.log('⏰ 计时器结束')
  
  // 先尝试从系统文本获取next_answernum
  const systemTexts = questionStore.getSystemTexts(questionStore.currentAnswerNum)
  let targetScript = systemTexts.length > 0 ? systemTexts[0] : null
  
  // 如果系统文本没有timer，尝试从选择选项获取
  if (!targetScript || !targetScript.timer) {
    const choices = questionStore.getChoices(questionStore.currentAnswerNum)
    if (choices.length > 0 && choices[0].timer) {
      targetScript = choices[0]
    }
  }
  
  if (targetScript && targetScript.next_answernum !== null) {
    if (targetScript.next_answernum === 0) {
      // 指向0，需要退出界面并保存当前进度
      console.log('⏸️ 计时器结束，指向0，退出界面并保存进度')
      
      if (userStore.user?.id) {
        await questionStore.saveCurrentPosition(userStore.user.id)
        console.log(`💾 保存当前进度: 问题${questionStore.currentAnswerNum}`)
        
        // 检查是否是章节最后一题，如果是则解锁下一章节
        if (isLastQuestionOfChapter()) {
          await unlockNextChapter()
        }
      }
      
      Message.success('计时结束！')
      // 返回章节列表
      goBack()
    } else {
      // 自动跳转到下一个问题
      console.log(`🔄 计时器结束，自动跳转到问题 ${targetScript.next_answernum}`)
      
      Message.success('计时结束，自动进入下一题')
      
      // 短暂延迟后跳转
      setTimeout(async () => {
        questionStore.currentAnswerNum = targetScript!.next_answernum!
        await loadCurrentQuestion()
      }, 300)
    }
  }
}

// 显示消息（直接显示，无打字机效果）
const streamMessage = async (message: any): Promise<void> => {
  try {
    // 获取完整内容
    const response = await scriptApi.getScriptText(message.id)
    
    if (!response.success || !response.data) {
      throw new Error(response.message || '获取内容失败')
    }
    
    const fullContent = response.data.content || ''
    
    // 创建消息对象并直接显示完整内容
    const displayMessage = reactive({
      id: message.id,
      content: fullContent,
      img: message.img || null,
      isUser: false,
      typing: false
    })

    displayMessages.value.push(displayMessage)
    
    // 增加完成计数
    messageCounter.value.completed++
    
    // 检查是否需要自动跳转
    checkAutoNextAfterStream()
    
  } catch (error) {
    console.error('获取内容错误:', error)
    
    // 降级到直接显示message中的内容
    const displayMessage = reactive({
      id: message.id,
      content: message.content || '',
      img: message.img || null,
      isUser: false,
      typing: false
    })

    displayMessages.value.push(displayMessage)
    
    // 增加完成计数（即使出错也要计数）
    messageCounter.value.completed++
    
    // 检查是否需要自动跳转
    checkAutoNextAfterStream()
  }
}

// 选择答案处理
const handleChoiceClick = async (choice: any) => {
  // 清理自动跳转定时器（用户主动选择）
  if (autoNextTimer.value) {
    clearTimeout(autoNextTimer.value)
    autoNextTimer.value = null
  }
  
  // 停止计时器（用户主动选择）
  stopTimer()
  
  // 添加用户选择的消息
  displayMessages.value.push({
    id: Date.now(),
    content: choice.content,
    isUser: true,
    typing: false
  })
  
  // 获取选择结果
  const result = questionStore.selectAnswer(choice.id)
  console.log('🎯 选择结果:', result)
  console.log('🔍 判断条件:', {
    'result.finished': result.finished,
    'result.needExit': result.needExit,
    'userStore.user?.id': userStore.user?.id,
    'result.saveProgressAt': result.saveProgressAt
  })
  
  if (result.finished && result.needExit) {
    // next_answernum为0，需要退出界面并保存当前进度
    console.log('⏸️ 选择指向0，退出界面并保存进度', {
      currentAnswerNum: questionStore.currentAnswerNum,
      saveProgressAt: result.saveProgressAt,
      currentChapter: questionStore.currentChapter
    })
    
    if (userStore.user?.id && result.saveProgressAt !== undefined) {
      // 保存当前问题编号
      await questionStore.saveCurrentPosition(userStore.user.id)
      console.log(`💾 保存当前进度: 问题${result.saveProgressAt}`)
      
      // 检查是否是章节最后一题，如果是则解锁下一章节
      const isLast = isLastQuestionOfChapter()
      console.log(`🔑 是否调用解锁: ${isLast}`)
      if (isLast) {
        await unlockNextChapter()
      } else {
        console.log(`❌ 不是最后一题，不解锁下一章节`)
      }
    }
    
    // 返回章节列表
    goBack()
  } else if (!result.finished) {
    // 正常跳转到下一个问题
    console.log(`➡️ 跳转到问题 ${result.nextQuestion}`)
    
    // 加载下一个问题
    await loadCurrentQuestion()
  }
}

// 用户输入处理
const handleInputSubmit = async () => {
  if (!userInput.value.trim()) return
  
  // 清理自动跳转定时器（用户主动输入）
  if (autoNextTimer.value) {
    clearTimeout(autoNextTimer.value)
    autoNextTimer.value = null
  }
  
  // 停止计时器（用户主动输入）
  stopTimer()
  
  const inputText = userInput.value.trim()
  
  // 添加用户输入的消息
  displayMessages.value.push({
    id: Date.now(),
    content: inputText,
    isUser: true,
    typing: false
  })
  
  // 清空输入框
  userInput.value = ''
  
  // 获取处理结果
  const result = questionStore.handleUserInput(inputText)
  console.log('📝 输入处理结果:', result)
  
  if (result.finished && result.needExit) {
    // next_answernum为0，需要退出界面并保存当前进度
    console.log('⏸️ 输入后指向0，退出界面并保存进度')
    
    if (userStore.user?.id && result.saveProgressAt !== undefined) {
      // 保存当前问题编号
      await questionStore.saveCurrentPosition(userStore.user.id)
      console.log(`💾 保存当前进度: 问题${result.saveProgressAt}`)
      
      // 检查是否是章节最后一题，如果是则解锁下一章节
      if (isLastQuestionOfChapter()) {
        await unlockNextChapter()
      }
    }
    
    // 返回章节列表
    goBack()
  } else if (!result.finished && result.nextQuestion !== undefined) {
    // 正常跳转到下一个问题
    console.log(`➡️ 跳转到问题 ${result.nextQuestion}`)
    
    // 加载下一个问题
    await loadCurrentQuestion()
  } else {
    // 找不到下一题，提示用户
    console.error('❌ 未找到下一题，无法跳转')
    Message.error('未找到下一题配置，请检查脚本设置')
  }
}

// 加载当前问题
const loadCurrentQuestion = async () => {
  console.log(`📖 加载问题${questionStore.currentAnswerNum}`)
  
  // 停止之前的计时器
  stopTimer()
  
  const systemTexts = questionStore.getSystemTexts(questionStore.currentAnswerNum)
  const choices = questionStore.getChoices(questionStore.currentAnswerNum)
  const needInputValue = questionStore.getNeedInput(questionStore.currentAnswerNum)
  
  console.log(`   - 系统文本数量: ${systemTexts.length}`)
  console.log(`   - 选择选项数量: ${choices.length}`)
  console.log(`   - 需要输入框: ${needInputValue}`)
  
  // 初始化消息计数器
  messageCounter.value = { total: systemTexts.length, completed: 0 }
  
  for (const text of systemTexts) {
    await streamMessage(text)
  }
  
  hasStarted.value = true
  
  // 如果当前问题有计时器设置，初始化计时器
  if (currentTimer.value) {
    initTimer()
  }
}

// 判断当前问题是否是章节的最后一题
const isLastQuestionOfChapter = () => {
  // 获取当前章节的所有问题编号
  const allAnswerNums = questionStore.scripts.map(s => s.answernum)
  const maxAnswerNum = Math.max(...allAnswerNums)
  
  // 当前问题编号等于最大问题编号，说明是最后一题
  const isLast = questionStore.currentAnswerNum === maxAnswerNum
  
  console.log(`🔍 检查是否是最后一题:`, {
    currentAnswerNum: questionStore.currentAnswerNum,
    maxAnswerNum,
    allAnswerNums: [...new Set(allAnswerNums)].sort((a, b) => a - b),
    isLast,
    scriptsCount: questionStore.scripts.length
  })
  
  return isLast
}

// 解锁下一章节
const unlockNextChapter = async () => {
  if (!userStore.user?.id) return
  
  const currentChapter = questionStore.currentChapter
  const nextChapter = currentChapter + 1
  
  console.log(`🔓 尝试解锁下一章节: 当前章节${currentChapter}, 下一章节${nextChapter}`)
  
  // 先设置完成章节标记（无论是否已经解锁，都需要显示问卷）
  console.log(`📝 设置完成章节标记: 章节${currentChapter}`)
  sessionStorage.setItem('chapterCompleted', 'true')
  sessionStorage.setItem('completedChapterNum', currentChapter.toString())
  console.log('📝 已设置 sessionStorage:', {
    chapterCompleted: sessionStorage.getItem('chapterCompleted'),
    completedChapterNum: sessionStorage.getItem('completedChapterNum')
  })
  
  // 检查下一章节是否已经解锁
  if (userStore.currentAllowNode > nextChapter) {
    console.log(`⚠️ 章节${nextChapter}已经解锁，无需重复解锁`)
    Message.success(`恭喜完成本章节！`)
    return
  }
  
  // 更新用户的allow_node
  try {
    const response = await userApi.updateUserProgress(userStore.user.id, nextChapter)
    
    if (response.success) {
      console.log(`✅ 成功解锁章节${nextChapter}`)
      
      // 刷新用户信息
      await userStore.refreshUserFromDB()
      
      Message.success(`恭喜完成本章节！已解锁下一章节`)
    } else {
      console.error('解锁章节失败:', response.message)
    }
  } catch (error) {
    console.error('解锁章节错误:', error)
  }
}

// 在消息显示完成后检查是否需要自动跳转到下一个问题
const checkAutoNextAfterStream = async () => {
  // 只有当所有消息都完成时才检查自动跳转
  if (messageCounter.value.completed < messageCounter.value.total) {
    return
  }
  
  console.log('🔍 所有消息显示完成，检查是否需要自动跳转')
  
  const choices = questionStore.getChoices(questionStore.currentAnswerNum)
  const needInputValue = questionStore.getNeedInput(questionStore.currentAnswerNum)
  
  // 如果没有选择选项且不需要输入，则自动跳转到下一个问题
  if (choices.length === 0 && !needInputValue) {
    // 找到当前问题组中的系统文本，获取其next_answernum
    const systemTexts = questionStore.getSystemTexts(questionStore.currentAnswerNum)
    
    if (systemTexts.length > 0) {
      const firstSystemText = systemTexts[0]
      
      if (firstSystemText.next_answernum === 0) {
        // 指向0，需要退出界面并保存当前进度
        console.log('⏸️ 纯文本问题指向0，退出界面并保存进度')
        
        if (userStore.user?.id) {
          await questionStore.saveCurrentPosition(userStore.user.id)
          console.log(`💾 保存当前进度: 问题${questionStore.currentAnswerNum}`)
          
          // 检查是否是章节最后一题，如果是则解锁下一章节
          if (isLastQuestionOfChapter()) {
            await unlockNextChapter()
          }
        }
        
        // 返回章节列表
        goBack()
      } else if (firstSystemText.next_answernum !== null) {
        // 自动跳转到下一个问题
        console.log(`🔄 纯文本问题自动跳转到问题 ${firstSystemText.next_answernum}`)
        
        // 添加一个短暂延迟，让用户能看到当前内容
        autoNextTimer.value = window.setTimeout(async () => {
          questionStore.currentAnswerNum = firstSystemText.next_answernum!
          await loadCurrentQuestion()
        }, 500) // 0.5秒后自动跳转
      }
    }
  }
}

// 初始化章节
const initChapter = async () => {
  const nodenum = parseInt(route.params.nodenum as string)
  
  if (isNaN(nodenum) || nodenum < 0 || nodenum > 8) {
    Message.error('无效的章节编号')
    goBack()
    return
  }
  
  loading.value = true
  
  try {
    // 获取用户记录的起始位置（这个方法内部已经会加载章节脚本）
    let startNum = 1
    if (userStore.user?.id) {
      const positionResult = await questionStore.getRememberPosition(userStore.user.id, nodenum)
      if (positionResult.success) {
        startNum = positionResult.startNum
        console.log(`📍 从记录位置开始: 第${startNum}题`)
      }
    } else {
      // 如果没有用户信息，直接加载章节脚本
      const loadResult = await questionStore.loadChapterScripts(nodenum, startNum)
      if (!loadResult.success) {
        Message.error(loadResult.message || '加载章节失败')
        goBack()
        return
      }
    }
    
    // 设置当前问题编号
    questionStore.currentAnswerNum = startNum
    questionStore.currentChapter = nodenum
    
    // 加载当前问题
    await loadCurrentQuestion()
    
  } catch (error) {
    console.error('初始化章节失败:', error)
    Message.error('初始化失败，请重试')
    goBack()
  } finally {
    loading.value = false
  }
}

// 显示图片查看模态框
const showImageModal = (src: string, alt: string) => {
  imageModal.src = src
  imageModal.alt = alt
  imageModal.visible = true
}

// 关闭图片查看模态框
const closeImageModal = () => {
  imageModal.visible = false
  imageModal.src = ''
  imageModal.alt = ''
}

// 保存退出位置（用于异常退出，如刷新、关闭页面）
const savePositionOnExit = async () => {
  if (userStore.user?.id && hasStarted.value) {
    // 异常退出时保存当前题目位置，用户下次进入时从当前题目继续
    await questionStore.saveCurrentPosition(userStore.user.id)
    console.log('💾 异常退出，已保存当前位置:', questionStore.currentAnswerNum)
  }
}

// 页面离开前保存位置
const handleBeforeUnload = () => {
  savePositionOnExit()
}

// 组件生命周期
onMounted(() => {
  // 初始化章节
  initChapter()

  // 监听页面刷新和关闭
  window.addEventListener('beforeunload', handleBeforeUnload)
})

onUnmounted(() => {
  // 清理定时器
  cleanupTimers()

  // 保存退出位置
  savePositionOnExit()

  // 移除事件监听
  window.removeEventListener('beforeunload', handleBeforeUnload)
})









</script>

<style scoped>
.question-page {
  margin: 0 auto;
  min-height: calc(100vh - 120px);
}

.question-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding: 16px 0;
  border-bottom: 1px solid #e5e6eb;
}

.back-btn {
  color: #4e5969;
}

.chapter-info {
  text-align: right;
}

.chapter-info h2 {
  margin: 0 0 8px 0;
  color: #1d2129;
  font-size: 18px;
  font-weight: 600;
}

.progress-bar {
  width: 200px;
}

.question-container {
  background: transparent;
  padding: 0;
  min-height: 400px;
  position: relative;
}

.message-area {
  margin-bottom: 32px;
}

.welcome-message {
  opacity: 0.8;
  margin-bottom: 20px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 20px;
}

.message-item.bot-message {
  justify-content: flex-start;
}

.message-item.user-message {
  justify-content: flex-end;
}

.message-item.typing .message-text::after {
  content: '▊';
  animation: typing-cursor 1.2s infinite;
  color: #165dff;
  font-weight: bold;
}

@keyframes typing-cursor {

  0%,
  45% {
    opacity: 1;
  }

  46%,
  100% {
    opacity: 0;
  }
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f2f3f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4e5969;
  flex-shrink: 0;
}

.user-avatar {
  background: #165dff;
  color: white;
}

.message-content {
  max-width: 70%;
}

.bot-message .message-content {
  max-width: 85%;
  align-self: flex-start;
}

.user-message .message-content {
  max-width: 70%;
  align-self: flex-end;
}

.bot-message .message-text {
  background: #f2f3f5;
  padding: 12px 16px;
  border-radius: 18px 18px 18px 4px;
  color: #1d2129;
  line-height: 1.5;
  font-size: 15px;
  text-align: left;
  word-break: break-word;
}

.user-message .message-text {
  background: #165dff;
  color: white;
  padding: 12px 16px;
  border-radius: 18px 18px 4px 18px;
  line-height: 1.5;
  font-size: 15px;
  text-align: left;
  word-break: break-word;
}

.typing-progress {
  margin-top: 8px;
  padding: 0 16px;
}

.timer-area {
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #f7f8fa;
  border-radius: 8px;
  border: 1px solid #e5e6eb;
}

.timer-display {
  display: flex;
  align-items: center;
  gap: 12px;
}

.timer-text {
  font-size: 18px;
  font-weight: 600;
  color: #1d2129;
  font-family: 'Courier New', monospace;
  flex: 1;
}

.choices-area {
  margin-top: 32px;
  padding: 24px;
  background: #f8faff;
  border-radius: 12px;
  border: 1px solid #e8f2ff;
}

.choices-area h3 {
  color: #1d2129;
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.choices-area h3 {
  padding-left: 0;
}

.choices-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.choice-item {
  background: #ffffff;
  border: 2px solid #e5e6eb;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 12px;
  position: relative;
  overflow: hidden;
}

.choice-item.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.choice-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 4px;
  background: #165dff;
  transform: scaleY(0);
  transition: transform 0.3s ease;
}

.choice-item:not(.disabled):hover {
  border-color: #165dff;
  background: #f8faff;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(22, 93, 255, 0.15);
}

.choice-item:not(.disabled):hover::before {
  transform: scaleY(1);
}

.choice-item:not(.disabled):active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.2);
}

.choice-content {
  flex: 1;
  color: #1d2129;
  font-size: 16px;
  line-height: 1.6;
  font-weight: 500;
  padding-right: 16px;
}

.choice-arrow {
  color: #86909c;
  font-size: 16px;
  transition: all 0.3s ease;
}

.choice-item:not(.disabled):hover .choice-arrow {
  color: #165dff;
  transform: translateX(4px);
}

.choice-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f2f3f5;
  color: #4e5969;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  margin-right: 16px;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.choice-item:not(.disabled):hover .choice-number {
  background: #165dff;
  color: white;
  transform: scale(1.1);
}

.typing-hint {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-top: 16px;
  color: #86909c;
  font-size: 14px;
}

.input-area {
  margin-top: 32px;
  padding: 24px;
  background: #f8faff;
  border-radius: 12px;
  border: 1px solid #e8f2ff;
}

.input-area h3 {
  color: #1d2129;
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-area h3 {
  padding-left: 0;
}

.input-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.user-input {
  font-size: 16px;
  line-height: 1.6;
  border: 2px solid #e5e6eb;
  border-radius: 8px;
  transition: border-color 0.3s ease;
}

.user-input:focus {
  border-color: #165dff;
  box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.1);
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.input-hint {
  color: #86909c;
  font-size: 14px;
  font-style: italic;
}

.submit-btn {
  height: 40px;
  padding: 0 24px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.submit-btn:not(:disabled):hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.3);
}

.message-image {
  margin-top: 12px;
  border-radius: 8px;
  overflow: hidden;
  max-width: 100%;
}

.question-image {
  width: 100%;
  max-width: 400px;
  height: auto;
  max-height: 300px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  cursor: pointer;
}

.question-image:hover {
  transform: scale(1.02);
}

.modal-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 80vh;
  overflow: hidden;
}

.modal-image {
  max-width: 100%;
  max-height: 80vh;
  width: auto;
  height: auto;
  object-fit: contain;
  border-radius: 8px;
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}


.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  z-index: 10;
}

.loading-content {
  text-align: center;
  color: #4e5969;
}

.loading-content p {
  margin-top: 16px;
  font-size: 14px;
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .question-page {
    padding: 0 16px;
  }

  .question-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .chapter-info {
    text-align: left;
    width: 100%;
  }

  .progress-bar {
    width: 100%;
  }

  .question-container {
    padding: 0;
  }

  .bot-message .message-content {
    max-width: 90%;
  }
  
  .user-message .message-content {
    max-width: 85%;
  }

  .choices-area {
    padding: 16px;
    margin-top: 20px;
  }

  .choice-item {
    padding: 16px;
  }

  .choice-content {
    font-size: 15px;
  }
  
  .input-area {
    padding: 16px;
    margin-top: 20px;
  }
  
  .input-container {
    padding: 16px;
  }
  
  .input-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .submit-btn {
    width: 100%;
  }
  
  .question-image {
    max-width: 300px;
    max-height: 200px;
  }
  
  .modal-image-container {
    max-height: 70vh;
  }
  
  .modal-image {
    max-height: 70vh;
  }
}
</style>